package com.example.park.ui.dashboard;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.example.park.Protocol;
import com.example.park.R;
import com.example.park.TcpClient;
import com.example.park.databinding.FragmentDashboardBinding;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/*
public class DashboardFragment extends Fragment {

    private FragmentDashboardBinding binding;
    private LinearLayout reservationContainer;
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        DashboardViewModel dashboardViewModel =
                new ViewModelProvider(this).get(DashboardViewModel.class);

        binding = FragmentDashboardBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        // 页面加载时发送预约记录请求
        try {
            JSONObject root_ = new JSONObject();
            JSONObject message = new JSONObject();

            SharedPreferences sharedPref = requireActivity().getSharedPreferences("UserPrefs", Context.MODE_PRIVATE);
            String username = sharedPref.getString("nickname", "");
            message.put("user", username);
            root_.put("func", 4);
            root_.put("message", message);

            String jsonString = root_.toString();
            String encodedMessage = Protocol.Encode(jsonString);
            TcpClient.getInstance().sendMessage(encodedMessage);

            // 模拟接收 JSON 数据，可替换为 TCP 回调中的处理逻辑
            String dummyResponse = "[{\"location\":\"A-1\",\"plate\":\"吉A12345\",\"start_time\":\"2025-04-20 23:00:00\",\"status\":\"available\"}," +
                    "{\"location\":\"A-2\",\"plate\":\"吉C12345\",\"start_time\":\"2025-04-21 12:00:00\",\"status\":\"available\"}]";

            displayReservations(dummyResponse, username);

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return root;
    }
    private void displayReservations(String jsonData, String username) {
        reservationContainer.removeAllViews();
        try {
            JSONArray reservations = new JSONArray(jsonData);
            for (int i = 0; i < reservations.length(); i++) {
                JSONObject item = reservations.getJSONObject(i);

                String location = item.optString("location");
                String plate = item.optString("plate");
                String time = item.optString("start_time");
                String status = item.optString("status");

                View block = createReservationBlock(location, plate, time, status, username);
                reservationContainer.addView(block);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private View createReservationBlock(String location, String plate, String time, String status, String username) {
        Context context = requireContext();
        LinearLayout block = new LinearLayout(context);
        block.setOrientation(LinearLayout.VERTICAL);
        block.setPadding(20, 20, 20, 20);
        block.setBackgroundResource(android.R.drawable.dialog_holo_light_frame);

        TextView textView = new TextView(context);
        textView.setText(String.format(
                "用户名：%s\n车牌号：%s\n停车位置：%s\n预约时间：%s\n状态：%s",
                username, plate, location, time, status
        ));
        textView.setTextSize(16);
        textView.setEllipsize(TextUtils.TruncateAt.END);
        textView.setMaxLines(6);

        block.addView(textView);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
        );
        params.setMargins(0, 0, 0, 30);
        block.setLayoutParams(params);

        return block;
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}
*/

public class DashboardFragment extends Fragment {

    private FragmentDashboardBinding binding;
    private LinearLayout reservationContainer;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        binding = FragmentDashboardBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        //初始化 reservationContainer
        reservationContainer = root.findViewById(R.id.reservation_container);


        fetchAndDisplayReservations();

        return root;
    }

    private void fetchAndDisplayReservations() {
        SharedPreferences sharedPref = requireActivity().getSharedPreferences("UserPrefs", Context.MODE_PRIVATE);
        String username = sharedPref.getString("nickname", "");

        JSONObject root = new JSONObject();
        JSONObject message = new JSONObject();

        try {
            message.put("user", username);
            root.put("func", 4);
            root.put("message", message);

            String encodedMessage = Protocol.Encode(root.toString());
            TcpClient.getInstance().sendMessage(encodedMessage);

        } catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "请求失败", Toast.LENGTH_SHORT).show();
        }

        new Thread(() -> {
            try {
                String response = TcpClient.getInstance().receiveMessage();
                if (response == null || response.isEmpty()) {
                    requireActivity().runOnUiThread(() ->
                            Toast.makeText(getActivity(), "未收到服务器响应", Toast.LENGTH_SHORT).show());
                    return;
                }

                StringBuilder remaining = new StringBuilder();
                String content;
                try {
                    content = Protocol.Decode(response, remaining);
                } catch (Exception decodeErr) {
                    decodeErr.printStackTrace();
                    requireActivity().runOnUiThread(() ->
                            Toast.makeText(getActivity(), "数据解码失败", Toast.LENGTH_SHORT).show());
                    return;
                }

                if (content == null || content.isEmpty()) {
                    requireActivity().runOnUiThread(() ->
                            Toast.makeText(getActivity(), "服务器返回数据为空", Toast.LENGTH_SHORT).show());
                    return;
                }

                // 确保解析成 JSON 数组，否则提示错误
                try {
                    JSONArray testArray = new JSONArray(content);
                } catch (JSONException arrayError) {
                    requireActivity().runOnUiThread(() ->
                            Toast.makeText(getActivity(), "返回数据格式不正确", Toast.LENGTH_SHORT).show());
                    return;
                }

                requireActivity().runOnUiThread(() -> {
                    displayReservations(content, username);
                });

            } catch (Exception e) {
                e.printStackTrace();
                requireActivity().runOnUiThread(() ->
                        Toast.makeText(getActivity(), "接收或解析服务器数据出错", Toast.LENGTH_SHORT).show());
            }
        }).start();
    }

    private void displayReservations(String jsonData, String username) {
        reservationContainer.removeAllViews();

        try {
            JSONArray reservations = new JSONArray(jsonData);
            for (int i = 0; i < reservations.length(); i++) {
                JSONObject item = reservations.getJSONObject(i);

                String location = item.optString("location");
                String plate = item.optString("plate");
                String time = item.optString("start_time");
                String status = item.optString("status");

                View block = createReservationBlock(location, plate, time, status, username);
                reservationContainer.addView(block);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private View createReservationBlock(String location, String plate, String time, String status, String username) {
        Context context = requireContext();
        LinearLayout block = new LinearLayout(context);
        block.setOrientation(LinearLayout.VERTICAL);
        block.setPadding(20, 20, 20, 20);
        block.setBackgroundResource(android.R.drawable.dialog_holo_light_frame);

        TextView textView = new TextView(context);
        textView.setText(String.format(
                "用户名：%s\n车牌号：%s\n停车位置：%s\n预约时间：%s\n状态：%s",
                username, plate, location, time, status
        ));
        textView.setTextSize(16);
        textView.setEllipsize(TextUtils.TruncateAt.END);
        textView.setMaxLines(6);

        block.addView(textView);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
        );
        params.setMargins(0, 0, 0, 30);
        block.setLayoutParams(params);

        return block;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}